package com.catazzz.springbootstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.catazzz.springbootstudy.entity.User;
import com.catazzz.springbootstudy.mapper.UserMapper;
import com.catazzz.springbootstudy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @作者: Tao
 * @日期: 2024/12/30
 * @时间: 10:14
 * @描述: 用户信息 服务实现类 <br><pre>
 *     1.findByName(name) - 根据姓名查询用户
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    public UserMapper mapper;

    /**
     * 根据姓名查询用户
     * @param name 姓名
     * @return 用户列表
     */
    @Override
    public List<User> findByName(String name) {
        return list(new QueryWrapper<User>().like("name", name));
    }

    /**
     * 添加用户
     * @param user 用户 <br> <pre>
     *        使用 @Transactional(propagation = Propagation.REQUIRED) 注解确保方法在事务中执行，如果当前没有事务则创建一个新的事务
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void addWithRequired(User user){
        mapper.insert(user);
    }

    /**
     * 添加用户并抛出异常
     * @param user 用户 <br> <pre>
     *        使用 @Transactional(propagation = Propagation.REQUIRED) 注解确保方法在事务中执行，如果当前没有事务则创建一个新的事务
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public void addWithRequiredAndException(User user){
        mapper.insert(user);
        throw new RuntimeException("添加用户时发生异常");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addWithRequiredNew(User user) {
        mapper.insert(user);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addWithRequiredNewAndException(User user) {
        mapper.insert(user);
        throw new RuntimeException();
    }

    @Override
    @Transactional(propagation = Propagation.NESTED)
    public void addWithNested(User user) {
        mapper.insert(user);
    }

    @Override
    @Transactional(propagation = Propagation.NESTED)
    public void addWithNestedAndException(User user) {
        mapper.insert(user);
        throw new RuntimeException();
    }
}
